package com.liancheng.smarthome.base;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.StringRes;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;

import com.liancheng.smarthome.R;
import com.liancheng.smarthome.manager.AppManager;
import com.liancheng.smarthome.utils.appcommon.UiUtils;
import com.liancheng.smarthome.utils.common.MvpInstantiationUtils;
import com.liancheng.smarthome.utils.logs.LogTag;
import com.liancheng.smarthome.utils.ui.ProgressDialog;


/**\
 * 基类的activity
 * @param <Bind>
 * @param <T>
 */
public abstract class BaseActivity<T extends BaseVM,Bind extends ViewDataBinding> extends AppCompatActivity {

    public Bind contentView;
    public Context context;
    public Activity activity;
    private String key;
    public T VM;
    private int statusBarHeight;

    @Override
    protected final void onCreate(Bundle savedInstanceState) {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//竖屏
        super.onCreate(savedInstanceState);
        if (cancelCreate()) {
            finish();
            return;
        }
        if(isHidenStatusbar()){
            //取消状态栏
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        }else {
            UiUtils.setStatusBarWHITE(this);
        }
        context = getBaseContext();
        activity = this;
        VM = MvpInstantiationUtils.getInstantiation(this, MvpInstantiationUtils.FIRSTGENERICITY);
        if (VM != null) {
            VM.bindViewAndModel(this);
        }
//        getStateBar3();
        contentView = DataBindingUtil.setContentView(activity, getLayoutId());
        initViewAndData();
        afterCreate();
//        CallBackManager.onCreate(activity);
        key = getClass().getName() + System.currentTimeMillis();
        AppManager.add(key, activity);
    }

    private void getStateBar3(){
        int result = 0;
        int resourceId = this.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = this.getResources().getDimensionPixelSize(resourceId);
        }
        LogTag.d("状态栏高度3：" + result + "px");
        statusBarHeight = result;
        View byId = findViewById(R.id.v_title_on);
        try{
            if(byId!=null){
                ViewGroup.LayoutParams params = byId.getLayoutParams();
                params.height=result;
                LogTag.d("setAct:"+this.getLocalClassName()+"-->"+params.height);
                byId.setLayoutParams(params);
            }else {
                LogTag.d("actName:"+this.getLocalClassName());
            }
        }catch (Exception e){
            e.printStackTrace();
            LogTag.d("actName:"+this.getLocalClassName());
        }
    }

    public int getStatusBarHeight() {
        return statusBarHeight;
    }
    /**
     * 用于控制当前界面是否隐藏状态栏（子类重写改变）
     *
     * @return
     */
    protected boolean isHidenStatusbar(){
        return false;
    }
    @Override
    protected void onResume() {
        super.onResume();
//        CallBackManager.onResume(activity);
    }

    @Override
    protected void onPause() {
        super.onPause();
//        CallBackManager.onPause(activity);
        dismissProcess();
    }

    @Override
    protected void onStop() {
        super.onStop();
//        CallBackManager.onStop(activity);
    }

    @Override
    protected void onDestroy() {
        if(VM != null)
            VM.freeObject();
        super.onDestroy();
        dismissProcess();
        dialog = null;
        contentView = null;
//        CallBackManager.onDestroy(activity);
        AppManager.delete(key);
        context = null;
        activity = null;
    }

    public abstract int getLayoutId();
    public abstract void afterCreate();
    protected void initViewAndData(){};

    public boolean cancelCreate() {
        return false;
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(R.anim.push_out, R.anim.push_right_out);
    }

    private ProgressDialog dialog;
    public Dialog getDialog() {
        if (dialog == null) dialog = new ProgressDialog(activity, getResString(R.string.net_loading_hint));
        return dialog;
    }

    public void showProcess(){
        Dialog dialog = getDialog();
        if (dialog != null) dialog.show();
    }

    public void dismissProcess(){
        if (dialog != null && dialog.isShowing()) dialog.cancel();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            backPress();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    public void backClick(View view) {
        backPress();
    }

    public void backPress() {
        finish();
    }

    public final String getResString (@StringRes int stringId) {
        try{
            return getResources().getString(stringId);
        }catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public final int getResColor(int color) {
        return getResources().getColor(color);
    }

    public boolean hasNull(){
        return contentView == null;
    }
    public void closeRefresh(){}

    /*
    * 在Activity中加载fragment时会要求实现onFragmentInteraction(Uri uri)方法
     * 此方法主要作用是从fragment向activity传递数据
     * mListener.onFragmentInteraction(Uri.parse("content://" + "com.fengge.demo" + "/people"));
     *  这时activity中就可以根据fragment中回传过来的uri标识进行相关操作。
     *
     */
    public interface OnFragmentInteractionListener {
        void onFragmentInteraction(Uri uri);
    }
//    public final void setTitleLabel (@StringRes int stringId) {
//        setTitleLabel(getResString(stringId));
//    }
//
//    public final void setTitleLabel (String title) {
//        CommonTitleBarView titleBarView = getTitleBarView();
//        if (titleBarView != null && titleBarView.titleText != null) {
//            titleBarView.titleText.set(title);
//        }
//    }
//
//    public CommonTitleBarView getTitleBarView() {
//        CommonTitleBar titleBar = getTitleBar();
//        return titleBar == null ? null : titleBar.getViewModel();
//    }
//
//    public CommonTitleBar getTitleBar() {
//        if (contentView instanceof ListActivityView) {
//            return ((ListActivityView) contentView).titleBar;
//        }
//        return null;
//    }
}
//    public <T> void getNetData(final Callback<T> callback, Call<T> call){
//        showProcess();
//        boolean result = HttpManager.send(new Callback<T>() {
//            @Override
//            public void onResponse(Call<T> call, Response<T> response) {
//                if (activity == null || contentView == null) {
//                    return;
//                }
//                dismissProcess();
//                if (callback != null) callback.onResponse(call, response);
//            }
//
//            @Override
//            public void onFailure(Call<T> call, Throwable t) {
//                if (activity == null || contentView == null) {
//                    return;
//                }
//                dismissProcess();
//                if (callback != null) callback.onFailure(call, t);
//            }
//        }, call);
//        if (!result) dismissProcess();
//    }
